package team.first.movieapiv2pro.service.impl;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import team.first.movieapiv2pro.dao.impl.AuthorizationDAOImpl;
import team.first.movieapiv2pro.domain.User;
import team.first.movieapiv2pro.service.AuthorizationService;
import team.first.movieapiv2pro.token.Token;
import team.first.movieapiv2pro.token.TokenType;
import team.first.movieapiv2pro.util.JWTHS256;

import java.time.Duration;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movieapiv2pro.service.impl
 * @Date: 2021/12/26 9:08
 * @Description:
 */
@Service
public class AuthorizationServiceImpl implements AuthorizationService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AuthorizationDAOImpl authorizationDAO;

    @Override
    public int register(User user) {
        // 注册前先检查这个账号是否存在
        if (authorizationDAO.isExist(user.getEmail())) {
            return 2;
        }

        // 不存在，可以注册
        boolean res = authorizationDAO.register(user);

        if (res) {
            // 一般刚注册完就会登录，所以设置一个用户的信息缓存,有效期5分钟
            stringRedisTemplate.opsForValue().set("data:movie-api-v2:user:" + user.getEmail(), JSON.toJSONString(user), Duration.ofSeconds(60 * 5));
            return 0;
        }
        return 1;
    }

    @Override
    public Token login(User user) {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();

        // 先看缓存里有没有该用户信息
        String userJson = operations.get("movie-api-v2:data:user:" + user.getEmail());

        User cacheUser = null;
        if (userJson != null) {
            cacheUser = JSON.parseObject(userJson, User.class);
        }
        int flag = 0;
        // 判断信息是否一致
        if (cacheUser != null && user.getEmail().equals(cacheUser.getEmail()) && user.getPassword().equals(cacheUser.getPassword())) {
            // 登录成功
            flag = 1;
            user.setRoleType(cacheUser.getRoleType());
        } else { // 查询数据库
            User login = authorizationDAO.selectUser(user);
            if (login != null) {
                user.setRoleType(login.getRoleType());
                flag = 1;
            } else {
                flag = 0;
            }
        }

        Token token = null;
        // 如果登录成功, 授予令牌
        if (flag == 1) {
            token = new Token();
            String tokenValue = null;
            if (user.getRoleType() == 0) {
                token.setTokenType(TokenType.SIMPLE);
            } else {
                token.setTokenType(TokenType.VIP);
                // 普通用户token有效期30分钟、VIP用户一小时
                token.setTtl(3600);
            }
            // 利用用户邮箱生成token
            tokenValue = JWTHS256.buildJWT(user.getEmail());
            token.setTokenValue(tokenValue).setUserEmail(user.getEmail());
            // java.time.Duration.ofSeconds(long seconds)方法获取表示秒数的Duration和以纳秒为单位的调整。
            operations.set("movie-api-v2:token:" + user.getEmail(), tokenValue, Duration.ofSeconds(token.getTtl()));
        }
        return token;
    }

    @Override
    public User getById(Integer userId) {
        return authorizationDAO.selectById(userId);
    }
}
